package cn.haoran.common.aspect;

import cn.haoran.common.exception.AppException;
import cn.haoran.common.utils.IPUtils;
import cn.haoran.modules.palaeobios.entity.Article;
import cn.haoran.modules.palaeobios.entity.LogEntity;
import cn.haoran.modules.palaeobios.entity.LogSheetEntity;
import cn.haoran.modules.sys.controller.AbstractController;
import cn.hutool.core.date.DateUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *  日志切面类
 *  用于记录用户的操作日志
 *  create to haoran 2020 1.15
 */
@Aspect
@Configuration
public class LogAspect extends AbstractController {
    @Autowired
    MongoTemplate mongoTemplate;
    protected static Logger logger= LoggerFactory.getLogger("日志切面");
    @Around("execution(* cn.haoran.modules.palaeobios.controller.ArticleController.*(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result = null;
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes)ra;
        assert sra != null;
        HttpServletRequest request = sra.getRequest();
        String ip = IPUtils.getIpAddr(request);
        // 获得实体
        point.getTarget();
        // 获得拦截的方法名
        String methodName = point.getSignature().getName();
            try{
                Object[] args = point.getArgs();
                /* 增删改方法时 插入一条日志记录 */
                switch (methodName) {
                    case "save": {
                        Article article = (Article) args[0];
                        String title = article.getTitle();
                        insertLog(methodName, title,ip);
                        break;
                    }
                    case "delete":
                        insertLog(methodName, Arrays.toString(args),ip);
                        break;
                    case "update": {
                        Article article = (Article) args[0];
                        String title = article.getTitle();
                        insertLog(methodName, title,ip);
                        break;
                    }
                }
                result = point.proceed();
            }catch (Exception e){
                throw new AppException("日志服务异常");
            }
            /* 查看文章时 新增统计记录 */
            if (methodName.equals("info")){
                insertLogSheet(result,ip);
            }
        return result;
    }



    private void insertLogSheet(Object result,String ip){
        Map<String,Object> map = (HashMap) result;
        Article article =(Article) map.get("article");
        LogSheetEntity logSheetEntity = new LogSheetEntity();
        logSheetEntity.setAId(article.getId().toString());
        logSheetEntity.setIp(ip);
        logSheetEntity.setCreateDate(DateUtil.today());
        logSheetEntity.setCreateDateTime(DateUtil.now());
        Date date = DateUtil.date();
        logSheetEntity.setDate(LocalDateTime.now());
        logSheetEntity.setPId(article.getColumnId().toString());
        logSheetEntity.setTitle(article.getTitle());
        mongoTemplate.insert(logSheetEntity);
    }
    /**
     * 插入一条日志信息
     */
    private void insertLog(String methodName,String args,String ip){
        LogEntity logEntity = new LogEntity();
        logEntity.setIp(ip);
        logEntity.setMethodName(methodName);
        logEntity.setCreateDateTime(DateUtil.now());
        logEntity.setCreateDate(DateUtil.today());
        logEntity.setContent(args);
        logEntity.setName(getUser().getUsername());
        mongoTemplate.insert(logEntity);
    }
}
